from pod.std import *
from pod.macros.html.util import tag
from structure import Join

# want to move Range to another place
from pod.grammar import RangeType
import collections

class Table(Macro):
    name = "table"
    doctype = "html"
    counter = 0

    def __init__(self, ctx, klass="default", border=None, label=None, style=None):
        super(Table, self).__init__()
        self.options = []
        self.klass = klass
        self.border = border
        self.number = Table.counter
        if label: ctx.env["label:%s" % label] = self
        
        Table.counter += 1
            
    def __call__(self, content):
        for i, el in enumerate(content):
            if isinstance(el, TableRowHolder):
                if i > 0 and i < len(content) + 1 and isinstance(content[i - 1], TableLineHolder):                    
                    el.setTopLine(True, content[i -1].positions)
                if i < len(content) - 1 and i < len(content) - 1 and isinstance(content[i + 1], TableLineHolder):
                    el.setBottomLine(True, content[i + 1].positions)
        
        table = tag("table", cols=len(content), klass="default")[
            [tag("tr", klass=self.klass)[str(row)] for row in content if isinstance(row, TableRowHolder)]
        ]
                
        return table

class TableLineHolder(object):
    def __init__(self, positions):
        self.positions = positions

class TableLine(Macro):
    name = "line"
    doctype = "html"
    
    def __init__(self, ctx, *positions):        
        if len(positions) == 0: self.positions = None
        elif isinstance(positions[0], RangeType): self.positions = positions[0]
        else: self.positions = positions
        
    def __call__(self, content):
        return TableLineHolder(self.positions)

class TableRowHolder(object):
    def __init__(self, cells):
        self.cells = cells
        self.topLine = False
        self.bottomLine = False
        
    def setTopLine(self, v, positions):
        if positions == None: self.topLine = v
        else: self.topLine = positions

    def setBottomLine(self, v, positions):
        if positions == None: self.bottomLine = v
        else: self.bottomLine = positions

    def __repr__(self):
        topPositions = self.topLine
        if topPositions == True: topPositions = range(len(self.cells))
        
        bottomPositions = self.bottomLine
        if bottomPositions == True: bottomPositions = range(len(self.cells))
        
        if topPositions != False:            
            for i, cell in enumerate(self.cells):
                if i in topPositions:
                    cell.setAttr("style", cell.getAttr("style") + "border-top: 1px solid black;")
            #endfor
        #endif
                    
        if bottomPositions != False:
            for i, cell in enumerate(self.cells):
                if i in bottomPositions:
                    cell.setAttr("style", cell.getAttr("style") + "border-bottom: 1px solid black;")
            #endfor
        #endif
                
        return "".join([str(cell) for cell in self.cells])
        #return Join(self.cells)
        
        
class Row(Macro):
    """
    border is a list that can take on the values: 
        top, bottom, all
    """
    name = "row"
    doctype = "html"

    def __init__(self, ctx, border=None):
        super(Row, self).__init__()
        self.border = border
        
    def __call__(self, content):
        blocks = sum([(isinstance(block, Block) or isinstance(block, TableHeaderHolder)) for block in content])
        decorators = [""] * (blocks+1)
        pos = 0
        for data in Macro.flatten(content):
            if isinstance(data, str):
                decorators[pos] = data.strip()
            else:
                pos += 1
        #endfor
        
        cells = []
        pos = 0
        for block in content:
            style = ""
            if isinstance(block, Block) or isinstance(block, TableHeaderHolder):
                if decorators[pos] == "|":
                    style += "border-left: 1px solid black;"
                if decorators[pos+1] == "|":
                    style += "border-right: 1px solid black;"
                if isinstance(block, Block):
                    cells.append(tag("td", klass="default", style=style)[Macro.flatten(block)])
                else:
                    cells.append(tag("th", klass="default", style=style)[Macro.flatten(block.content)])
                pos += 1
        #endfor
        return TableRowHolder(cells)

class TableHeaderHolder(object):
    def __init__(self, content):
        self.content = content        

class TableHeader(Macro):
    name = "th"
    doctype = "html"
    
    def __init__(self, ctx):
        super(TableHeader, self).__init__()
        
    def __call__(self, content):
        return TableHeaderHolder(content)
